package com.dfy.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dfy.common.Result;
import com.dfy.dto.SpotDTO;
import com.dfy.dto.SpotRequest;
import com.dfy.dto.SpotSearchRequest;
import com.dfy.dto.SpotResponse;
import com.dfy.dto.HomePageResponse;
import com.dfy.dto.SpotDetailResponse;
import com.dfy.entity.Spot;
import com.dfy.service.SpotService;
import com.dfy.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/spots")
public class SpotController {

    @Autowired
    private SpotService spotService;

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<SpotDTO> updateSpot(@PathVariable Long id, @Validated @RequestBody SpotRequest request) {
        if (request.getId() != null && !request.getId().equals(id)) {
            throw new BusinessException(400, "路径参数ID与请求体ID不一致");
        }
        request.setId(id);
        return Result.success(spotService.updateSpot(id, request));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> deleteSpot(@PathVariable Long id) {
        // 检查 id 是否有效
        if (id == null || id.toString().equals("undefined")) {
            throw new BusinessException(400, "无效的景点ID");
        }
        
        // 检查景点是否存在
        Spot spot = spotService.getById(id);
        if (spot == null) {
            throw new BusinessException(404, "景点不存在");
        }
        
        spotService.deleteSpot(id);
        return Result.success("删除成功");
    }

    @GetMapping
    public Result<Page<SpotDTO>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        log.info("分页查询景点列表，页码：{}，每页数量：{}", current, size);
        
        Page<Spot> page = new Page<>(current, size);
        LambdaQueryWrapper<Spot> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Spot::getCreatedAt);
        
        // 使用新实现的getSpotPage方法
        Page<SpotDTO> result = spotService.getSpotPage(page, wrapper);
        return Result.success(result);
    }

    @GetMapping("/category/{categoryType}")
    public Result<List<Spot>> getSpotsByCategory(@PathVariable String categoryType) {
        return Result.success(spotService.getSpotsByCategory(categoryType));
    }

    @PostMapping("/search")
    public Result<List<Spot>> searchSpots(@RequestBody SpotSearchRequest request) {
        return Result.success(spotService.searchSpots(request));
    }

    @GetMapping("/home")
    public Result<HomePageResponse> getHomePageData(
        @RequestParam(required = false) String keyword,
        @RequestParam(required = false) String type,
        @RequestParam(required = false) String categoryType
    ) {
        log.info("获取首页数据，关键：{}，类型：{}，分类：{}", keyword, type, categoryType);
        HomePageResponse response = spotService.getHomePageData(keyword, type, categoryType);
        return Result.success(response);
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> createSpot(@RequestBody @Validated SpotRequest request) {
        log.info("处理景点请求: {}", request);
        
        // 如果请求中包含ID，转向更新流程
        if (request.getId() != null) {
            log.info("检测到ID，转向更新流程");
            return Result.success(spotService.updateSpot(request.getId(), request));
        }
        
        // 否则创建新景点
        return Result.success(spotService.createSpot(request));
    }

    @GetMapping("/users/{userId}/favorites")
    public Result<List<SpotResponse>> getUserFavorites(
            @PathVariable String userId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        try {
            // 如果是 undefined，使用当前登录用户的 ID
            Long uid;
            if ("undefined".equals(userId)) {
                String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
                uid = Long.parseLong(currentUserId);
            } else {
                uid = Long.parseLong(userId);
            }
            
            log.info("获取用户{}的收藏列表", uid);
            List<SpotResponse> favorites = spotService.getUserFavorites(uid, pageNum, pageSize);
            return Result.success(favorites);
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的用户ID");
        }
    }

    @PostMapping("/users/{userId}/favorites/{spotId}")
    @PreAuthorize("hasRole('USER')")
    public Result<?> addFavorite(
            @PathVariable String userId,
            @PathVariable String spotId) {
        try {
            String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
            Long uid = Long.parseLong(userId);
            Long sid = Long.parseLong(spotId);
            
            // 验证用户权限
            if (!currentUserId.equals(userId)) {
                throw new BusinessException(403, "无权操作其他用户的收藏");
            }
            
            log.info("用户{}添加收藏，景点ID：{}", uid, sid);
            spotService.addFavorite(uid, sid);
            return Result.success("添加收藏成���");
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的ID参数");
        }
    }

    @DeleteMapping("/users/{userId}/favorites/{spotId}")
    @PreAuthorize("hasRole('USER')")
    public Result<?> removeFavorite(
            @PathVariable String userId,
            @PathVariable String spotId) {
        try {
            String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
            Long uid = Long.parseLong(userId);
            Long sid = Long.parseLong(spotId);
            
            // 验证用户权限
            if (!currentUserId.equals(userId)) {
                throw new BusinessException(403, "无权操作其他用户的收藏");
            }
            
            log.info("用户{}取消收藏，景点ID：{}", uid, sid);
            spotService.removeFavorite(uid, sid);
            return Result.success("取消收藏成功");
        } catch (NumberFormatException e) {
            throw new BusinessException(400, "无效的ID参数");
        }
    }

    @GetMapping("/{id}")
    public Result<SpotDetailResponse> getSpotById(@PathVariable Long id) {
        if (id == null) {
            throw new BusinessException(400, "景点ID不能为空");
        }
        return Result.success(spotService.getSpotDetail(id));
    }

    // 管理员专用接口 - 获取景点详细信息（包含所有状态的景点）
    @GetMapping("/admin/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<SpotDTO> getSpotByIdForAdmin(@PathVariable Long id) {
        log.info("管理员获取景点详情，id：{}", id);
        return Result.success(spotService.getSpotDetail(id));
    }
} 